package server

import (
	"context"
	"customer/internal/service"
	"github.com/go-kratos/kratos/v2/errors"
	"github.com/go-kratos/kratos/v2/middleware"
	"github.com/go-kratos/kratos/v2/middleware/auth/jwt"
	"github.com/go-kratos/kratos/v2/transport"
	jwt4 "github.com/golang-jwt/jwt/v4"
	"strings"
)

func customerJWT(customerService *service.CustomerService) middleware.Middleware {
	return func(handler middleware.Handler) middleware.Handler {
		return func(ctx context.Context, req interface{}) (interface{}, error) {
			//1获取被存储在jwt中的用户id
			claims, ok := jwt.FromContext(ctx)
			if !ok {
				return nil, errors.Unauthorized("unauthorized", "claims not found")
			}
			//2断言使用
			claimsMap := claims.(jwt4.MapClaims)
			id := claimsMap["jti"]
			//获取id对应的顾客的token
			token, err := customerService.CD.GetToken(id)
			if err != nil {
				return nil, errors.Unauthorized("unauthorized", "customer not found")
			}
			//3比对数据库表中的token与请求中的token是否一致
			header, _ := transport.FromServerContext(ctx)
			auths := strings.SplitN(header.RequestHeader().Get("Authorization"), " ", 2)
			jwttoken := auths[1]
			if jwttoken != token {
				return nil, errors.Unauthorized("unauthorized", "token was update")
			}
			//校验通过，继续执行下一个中间件
			return handler(ctx, req)
		}

	}
}
